import datetime
import logging
import time
from   qmt_tool.doris_tool import DbTool
import  requests,json
import pandas as pd
from sqlalchemy import create_engine,types,text
from qmt_tool.confile_tool import get_config_signal_file
import duckdb
import  akshare as ak

def get_notifiy_url_fromconf(url_name):
    signal_json=get_config_signal_file()
    url=signal_json[url_name]
    if url=='':
        print('没有配置该群的通知信号,请检查配置文件')
    return url

def get_stock_today_signal_fromdb_first(dbengine,symbol,strategy_nm,data_dt):
    sql_comm="select signal.trade_date,signal.symbol,signal.close,signal.name,signal.industry,signal.circ_mv,signal.amount,signal.turnover_rate,signal.zhangdiefu,gainian.ths_hy_nm,gainian.ths_gn_nm,gainian.em_gn_nm " + \
             "from quant_result.stock_signal_moni signal,quant.my_stock_hangye_gainian gainian where signal.symbol=:symbol and strategy_nm=:strategy_nm and  trade_date=:data_dt and version='1' and signal.symbol=gainian.symbol"
    try:
      df=pd.read_sql(text(sql_comm),dbengine,params={"data_dt":data_dt,"symbol":symbol,"strategy_nm":strategy_nm})
      return  df
    except Exception as e:
        print('读取数据出错', e)


def markdown_feishu_notify_first(symbol,url_name,dbengine,data_dt,zhibiao_name,buy_inform=''):
    data_pd=get_stock_today_signal_fromdb_first(dbengine=dbengine,symbol=symbol,strategy_nm=zhibiao_name,data_dt=data_dt)
    url_pd=get_notifiy_url_fromconf(url_name)
    url=url_pd.url[0]

    for row in data_pd.itertuples():

        trade_date=row.trade_date
        symbol=row.symbol
        name=row.name
        price=row.close
        circ_mv=row.circ_mv
        amount = round(row.amount / 100000000, 1)
        turnover_rate=row.turnover_rate
        zhangdiefu=row.zhangdiefu
        hangye=row.em_hy_nm
        em_gn=row.em_gn_nm
        stock_info = "http://www.iwencai.com/unifiedwap/result?w=" + str(symbol) + '&querytype=stock'
        stock_date="数据日期 :"+str(trade_date) + '\n'
        stock_code="股票代码：" + str(symbol) + ' '
        stock_name=" "+ str(name) + '\n'
        stock_price="当前价格：" + str(price) + '\n'
        stock_shizhi='流通市值：' + str(circ_mv)  + '亿   '
        stock_amount = '成交额：' + str(amount) + '亿 '
        stock_turoverrate="流通换手率：" + str(turnover_rate) + '%\n'
        stock_zhangdiefu="当前涨跌：" +str(zhangdiefu)
        ths_hangye="所属行业：" + hangye + "\n"
        em_gainian="东财概念： " + em_gn+ "\n\n"
        if buy_inform =='':
            buy_inform='还没写买卖策略，后面补充'
        else:
            buy_inform=buy_inform
        rich_text = { "msg_type": "post", "content": { "post": {"zh_cn": { "title": zhibiao_name,
                    "content": [ [  { "tag": "text","text": stock_date },
                            {"tag": "text",  "text": stock_code},
                            {"tag": "text","text": stock_name },
                            {"tag": "text","text": stock_price},
                            {"tag": "text", "text": stock_zhangdiefu},
                            {"tag": "text", "text": stock_shizhi},
                            {"tag": "text", "text": stock_amount},
                             {"tag": "text","text": stock_turoverrate},
                            {"tag": "text", "text": ths_hangye},
                            {"tag": "text", "text": em_gainian},
                            {"tag": "text","text": buy_inform},
                            {"tag": "a","text": "个股更多信息查看","href": stock_info }
                        ]] } } }}
        headers = {'Content-Type': 'application/json'}
        response = requests.request("POST", url, headers=headers, data=json.dumps(rich_text))
        if response.ok:
            print("飞书消息发送成功")
        else:
            print("飞书消息发送失败")
        print(response.text)
        time.sleep(1)



def writedb_and_feishu(buy_data,data_dt,qun_name,strategy_nm,buy_inform):

    etl_tm=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    data_update_todb = buy_data[
        ['trade_date','strategy_nm', 'symbol', 'name', 'industry', 'is_buy', 'circ_mv','amount', 'turnover_rate', 'close','zhangdiefu']]
    # data_update_todb['etl_tm']=etl_tm
    data_update_todb.insert(loc=11,column='etl_tm',value=etl_tm)
    is_today_signal = buy_data[-1:]['trade_date'].values[0].strftime('%Y%m%d') == data_dt

    if is_today_signal:
        # 发送到群中
        try:
            dbtool=DbTool()
            dbengine = dbtool.get_dbengine_quant()
            today_data=data_update_todb[-1:][:]
            dbtool.save_to_mysql_append(today_data, dbengine, table_name='stock_signal_moni')
            symbol=today_data.symbol[0]
            logging.error("{},{},{}".format(today_data['trade_date'].values[0],today_data['strategy_nm'].values[0],today_data['name'].values[0]))
            markdown_feishu_notify_first(symbol=symbol,url_name=qun_name,dbengine=dbengine,data_dt=data_dt,zhibiao_name=strategy_nm,buy_inform=buy_inform)
        except Exception as e:
            print("这里保存和发送数据，出错了",e)
    else:
        pass


def get_stock_today_signal_jhjj_from_tdxdb(dbengine):

    # jjak_df=ak.stock_zh_a_spot_em()
    sql_comm="""
select tdx.trade_date,tdx.symbol,tdx.strategy_name,tdx.buy_inform,IFNULL(asjs.name,"后端无数") name,ifnull (asjs.open,1) open,ifnull(asjs.zhangdiefu,0) zhangdiefu, ifnull(asjs.amount,10000) amount ,ifnull(asjs.turnover_rate,1) turnover_rate ,round(ifnull(asjs.float_value,100000000)/100000000) float_value,
gn.em_hy_nm, gn.em_gn_nm from 
(select trade_date,symbol,strategy_name,buy_inform from stock_signal_tdx_jhjj  
where trade_date=current_date()) tdx 
left join 
(select symbol,name,open,zhangdiefu,amount ,turnover_rate ,round(float_value/100000000) float_value
 from  quant.ak_stock_jhjj_snapshot  where trade_date=current_date())asjs 
on     tdx.symbol=asjs.symbol 
left join 
quant.my_stock_hangye_gainian gn
on tdx.symbol=gn.symbol 


"""
#     sql_comm2="""select tdx.trade_date,tdx.symbol,tdx.strategy_name,tdx.buy_inform,gn.em_hy_nm, gn.em_gn_nm from stock_signal_tdx_jhjj tdx
#               left join
# quant.my_stock_hangye_gainian gn
# on tdx.symbol=gn.symbol and tdx.trade_date=current_date()"""
    try:
      db_df=pd.read_sql(text(sql_comm),dbengine)

      # 使用duckdb 关联  db_df 和 jjak_df 得到一个新的表
      # new_df=duckdb.query(sql_comm2).to_df()
      return  db_df
    except Exception as e:
        print ('读取数据出错',e)
def tdx_jhjj_feishu_notify(url_name="竞价通知群"):
    dbengine=DbTool().get_dbengine_quant_result()
    data_pd=get_stock_today_signal_jhjj_from_tdxdb(dbengine=dbengine)
    url=get_notifiy_url_fromconf(url_name)


    for row in data_pd.itertuples():

        trade_date=row.trade_date
        symbol=row.symbol
        name=row.name
        price=row.open
        circ_mv=row.float_value
        amount = round(row.amount / 10000, 1)
        turnover_rate=row.turnover_rate
        zhangdiefu=row.zhangdiefu
        hangye=row.em_hy_nm
        if hangye==None:
            hangye='暂无'

        em_gn=row.em_gn_nm
        if em_gn ==None:
            em_gn='暂无'
        strategy_nm=row.strategy_name
        buy_inform=row.buy_inform
        stock_info = "http://www.iwencai.com/unifiedwap/result?w=" + str(symbol) + '&querytype=stock'
        stock_date="数据日期 :"+str(trade_date) + '\n'
        stock_code="股票代码：" + str(symbol) + ' '
        stock_name=" "+ str(name) + '\n'
        stock_price="当前价格：" + str(price) + '\n'
        stock_shizhi='流通市值：' + str(circ_mv)  + '亿   '
        stock_amount = '竞价成交额：' + str(amount) + '万 '
        stock_turoverrate="换手率：" + str(turnover_rate) + '%\n'
        stock_zhangdiefu="涨跌幅：" +str(zhangdiefu)
        ths_hangye="所属行业：" + hangye + "\n"
        em_gainian="东财概念： " + em_gn+ "\n\n"
        if buy_inform =='':
            buy_inform='还没写买卖策略，后面补充'
        else:
            buy_inform=buy_inform
        rich_text = { "msg_type": "post", "content": { "post": {"zh_cn": { "title": strategy_nm+stock_name,
                    "content": [ [  { "tag": "text","text": stock_date },
                            {"tag": "text",  "text": stock_code},
                            {"tag": "text","text": stock_name },
                            {"tag": "text","text": stock_price},
                            {"tag": "text", "text": stock_zhangdiefu},
                            {"tag": "text", "text": stock_shizhi},
                            {"tag": "text", "text": stock_amount},
                             {"tag": "text","text": stock_turoverrate},
                            {"tag": "text", "text": ths_hangye},
                            {"tag": "text", "text": em_gainian},
                            {"tag": "text","text": buy_inform},
                            {"tag": "a","text": "个股更多信息查看","href": stock_info }
                        ]] } } }}
        headers = {'Content-Type': 'application/json'}
        response = requests.request("POST", url, headers=headers, data=json.dumps(rich_text))
        if response.ok:
            print("飞书消息发送成功")
        else:
            print("飞书消息发送失败")
        print(response.text)
        time.sleep(1)

if __name__ == '__main__':
    dbengine = DbTool().get_dbengine_quant_result()
    get_stock_today_signal_jhjj_from_tdxdb(dbengine)